package com.elmcode.server.service.impl;

import com.elmcode.server.constant.StatusConst;
import com.elmcode.server.dto.CustomerSaveInfo;
import com.elmcode.server.entity.UserEntity;
import com.elmcode.server.exception.BusException;
import com.elmcode.server.exception.ParamsException;
import com.elmcode.server.exception.UserException;
import com.elmcode.server.properties.JWTProperties;
import com.elmcode.server.utils.JWTUtil;
import com.elmcode.server.utils.Result;
import com.elmcode.server.vo.CustomerVo;
import com.elmcode.server.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elmcode.common.utils.PageUtils;
import com.elmcode.common.utils.Query;

import com.elmcode.server.dao.CustomerDao;
import com.elmcode.server.entity.CustomerEntity;
import com.elmcode.server.service.CustomerService;

@Slf4j
@Service("customerService")
public class CustomerServiceImpl extends ServiceImpl<CustomerDao, CustomerEntity> implements CustomerService {

    @Autowired
    private JWTProperties jwtProperties;

    /**
     * elmcode:
     *   default:
     *     password: 123456
     */
    @Value("${elmcode.default.password}")
    private String defaultPassword;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CustomerEntity> page = this.page(
                new Query<CustomerEntity>().getPage(params),
                new QueryWrapper<CustomerEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public Map<String,Object> login(String phone, String password) {
        Map<String,Object> data = new HashMap<>();
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(password)){
            throw new ParamsException("账号或者密码不能为空");
        }
        QueryWrapper<CustomerEntity> queryWrapper = new QueryWrapper<CustomerEntity>().eq("phone",phone);

        CustomerEntity customerEntity = this.baseMapper.selectOne(queryWrapper);

        //TODO 加密
        if(customerEntity != null){
            //1、获取数据的password
            String passwordDb = customerEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //2、密码匹配
            boolean matches = passwordEncoder.matches(password,passwordDb);
            //登录成功
            if(matches){
                CustomerVo customerVo = new CustomerVo();
                BeanUtils.copyProperties(customerEntity,customerVo);
                log.info("登录成功:{}",customerVo);

                Map<String,Object> payload = new HashMap<>();
                payload.put(JWTUtil.CUSTOMER_ID,customerVo);
                String token = JWTUtil.generateToken(payload, jwtProperties.getJwtKey(), jwtProperties.getJwtTokenExpire());

                data.put("token",token);
                data.put("customerInfo",customerVo);

                return data;
            }
        }
        throw new BusException("账号或者密码错误");
    }

    @Override
    public void saveCustomer(CustomerSaveInfo customerSaveInfo) {
        //TODO 查询当前系统是否存在当前用户
        QueryWrapper<CustomerEntity> queryWrapper = new QueryWrapper<>();

        if(customerSaveInfo.getName() != null){
            queryWrapper.eq("name",customerSaveInfo.getName());
        }
        if(customerSaveInfo.getPhone() != null){
            queryWrapper.or().eq("phone",customerSaveInfo.getPhone());
        }

        CustomerEntity customer = this.baseMapper.selectOne(queryWrapper);
        if(customer == null){
            CustomerEntity customerEntity = new CustomerEntity();
            BeanUtils.copyProperties(customerSaveInfo,customerEntity);

            customerEntity.setCreateTime(new Date());
            //TODO 默认为男
            customerEntity.setSex("男");

            // 密码要进行加密存储
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encode = passwordEncoder.encode(defaultPassword);
            customerEntity.setPassword(encode);

            this.save(customerEntity);
        }else {
            throw new UserException("用户已经存在");
        }
    }

    @Override
    public CustomerEntity getCustomerByConsignee(String consignee) {

        QueryWrapper<CustomerEntity> queryWrapper = new QueryWrapper<CustomerEntity>()
                .eq("consignee",consignee);
        CustomerEntity customerEntity = this.baseMapper.selectOne(queryWrapper);
        return customerEntity;
    }

}